package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.entity.EmpBrand;
import com.ramos.kuaixiao.entity.ShopNew;
import com.ramos.kuaixiao.entity.ShopTypeBean;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class BrandDB {
    private static String TAG = "BrandDB";
    private static String TABLE_NAME = "NewBrand";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "brandId" + " CHAR(30)  PRIMARY KEY," + "brandName" + " CHAR(30),"
                + "disable" + " CHAR(10),"+ "modifyTime" + " Long);";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllBrand(List<ShopNew> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM NewBrand");
        String sql = "insert into NewBrand(brandId,brandName,disable,modifyTime) values(?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getBrandId() + "");
            stmt.bindString(2, customer.get(i).getBrandName() + "");
            stmt.bindString(3, customer.get(i).getDisable() + "");
            stmt.bindString(4, customer.get(i).getModifyTime() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllBrand(List<ShopNew> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllBrand:" + customer.size());
        for (int i = 0; i < customer.size(); i++) {
            ShopNew firstWarehouse = customer.get(i);
            ContentValues cv = new ContentValues();
            String[] infos = Utils.replaceStr(firstWarehouse.getBrandId() + "").split("_");
            int length = infos.length;
            cv.put("brandId", infos[length -1] + "");
            cv.put("brandName", firstWarehouse.getBrandName() + "");
            cv.put("disable", firstWarehouse.getDisable() + "");
            cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
            db.insertWithOnConflict("NewBrand",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ;

            // 生成的sql是 INSERT INTRO OR REPLACE INTO 这样的 (如果存在就替换存在的字段值. 存在的判断标准是主键冲突, 这里的主键是userId). 下面会介绍这个地方的方法
            //db.insertWithOnConflict("StoreNum",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ; //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public List<ShopNew> findAllBrand() {
        List<ShopNew> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from NewBrand", new String[]{});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            if(cursor.getString(2).equals("1")) {
                ShopNew customer = new ShopNew();
                customer.setBrandId(cursor.getString(0));
                customer.setBrandName(cursor.getString(1));
                customer.setDisable(cursor.getString(2));
                customer.setModifyTime(cursor.getLong(3));
                list.add(customer);
            }
        }
        cursor.close();
        Log.d(TAG, "findAllCustomer:" + list.size());
        return list;
    }

    public List<ShopNew> findAllNoEmptyBrand() {
        List<ShopTypeBean.ShopType.ProductInfo> shops = new ShopsDB().findAllShops();
        List<ShopNew> tmpList1 = new ArrayList<>();
        Set<String> tmpList2 = new HashSet<>();
        for (ShopTypeBean.ShopType.ProductInfo productInfo : shops) {
            tmpList2.add(productInfo.getBrandId());
        }
        Set<String> tmpList3 = new HashSet<>();
        List<ShopNew> list = findAllBrand();
        for (String s : tmpList2) {
            for(ShopNew shopNew : list){
                if(s.equals(shopNew.getBrandId())){
                    tmpList3.add(s);
                    break;
                }
            }
        }
        CommUtil.d(App.mContext, TAG, "tmpList2:" + tmpList2.size() + ","+"tmpList3:" + tmpList3.size());
        for (String s : tmpList3) {
            for(ShopNew shopNew : list){
                if(s.equals(shopNew.getBrandId())){
                    ShopNew shopNew1 = new ShopNew();
                    shopNew1.setBrandId(shopNew.getBrandId());
                    shopNew1.setBrandName(shopNew.getBrandName());
                    tmpList1.add(shopNew);
                    break;
                }
            }
        }
        CommUtil.d(App.mContext, TAG, "tmpList1:" + tmpList1.size());

        String brandList= "";
        List<ShopNew> tmpList = new ArrayList<>();
        List<EmpBrand> list1 = new EmpBrandDB().findAllCustomer();
        if(list1.size() == 0){
            tmpList.addAll(tmpList1);
        } else {
            if(list1.size() > 0 && tmpList1.size() > 0) {
                for (EmpBrand empStoreHouse : list1) {
                    if (empStoreHouse.getEmpId().equals(SharedPreference.getPreferString("id"))) {
                        brandList = empStoreHouse.getBrandList();
                    }
                }
                Log.d(TAG, "brandList:" + brandList);
                if (!StringUtil.isEmpty(brandList)) {
                    String[] list2 = brandList.split("_");
                    if (list2.length > 0) {
                        for (String s : list2) {
                            for (ShopNew wareHouse : tmpList1) {
                                if (s.equals(wareHouse.getBrandId())) {
                                    Log.d(TAG, "ShopNew:" + s + ","+wareHouse.getBrandName());
                                    tmpList.add(wareHouse);
                                }
                            }
                        }
                    }
                } else {
                    tmpList.addAll(tmpList1);
                }
            }
        }
        CommUtil.d(App.mContext, TAG, "tmpList:" + tmpList.size());
        return tmpList;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from NewBrand ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {
            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public String getProducts(String brandId) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from NewBrand where brandId =?", new String[]{brandId});
        if (cursor.moveToFirst()) {
            String product = cursor.getString(3);
            Log.d(TAG, "hasProducts true:" + product);
            cursor.close();
            if (StringUtil.isEmpty(product)) {
                return null;
            } else {
                return product;
            }
        }
        return null;
    }


    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM NewBrand");
        Log.d(TAG, "deleteAllNewBrand ");
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from NewBrand", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasBrand true");
            return true;
        } else {
            Log.d(TAG, "hasBrand false");
            cursor.close();
            return false;
        }
    }

}
